package com.jzo2o.trade.service.impl;

import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.trade.config.WeChatPayProperties;
import com.jzo2o.trade.enums.RefundStatusEnum;
import com.jzo2o.trade.model.domain.RefundRecord;
import com.jzo2o.trade.service.IRefundRecordService;
import com.jzo2o.trade.service.ITradingService;
import com.jzo2o.trade.service.IWxRefundService;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@Slf4j
public class WxRefundServiceImpl implements IWxRefundService {

    @Autowired
    private Config config;
    @Autowired
    private WeChatPayProperties weChatPayProperties;
    @Autowired
    private IRefundRecordService refundRecordService;
    @Autowired
    private ITradingService tradingService;


    @Override
    public ExecutionResultResDTO refund(RefundRecord refundRecord) {
        log.info("微信退款开始");
        RefundService refundService = new RefundService.Builder().config(config).build();
        CreateRequest createRequest = new CreateRequest();
        //设置退款参数
        createRequest.setOutTradeNo(refundRecord.getTradingOrderNo());
        createRequest.setOutRefundNo(String.valueOf(refundRecord.getRefundNo()));
        AmountReq amountReq = new AmountReq();
        amountReq.setTotal(refundRecord.getTotal().multiply(new BigDecimal(100)).longValue());
        amountReq.setRefund(refundRecord.getRefundAmount().multiply(new BigDecimal(100)).longValue());
        amountReq.setCurrency("CNY");
        createRequest.setAmount(amountReq);
        createRequest.setReason("取消订单退款");
        createRequest.setNotifyUrl(weChatPayProperties.getRefundNotifyUrl());
        //发起退款
        Refund refund = refundService.create(createRequest);
        log.info("微信退款结果：{}", refund);
        ExecutionResultResDTO executionResultResDTO = new ExecutionResultResDTO();
        executionResultResDTO.setRefundNo(Long.valueOf(refund.getOutRefundNo()));
        executionResultResDTO.setRefundId(refund.getRefundId());
        executionResultResDTO.setRefundStatus(RefundStatusEnum.SENDING.getCode());
        return executionResultResDTO;
    }
}
